from flask import Flask, request, jsonify, Response
import threading
from werkzeug.serving import make_server
import time
from urllib.parse import unquote


class AdvancedMockServer:
    def __init__(self, port=5000, host='0.0.0.0'):
        self.app = Flask(__name__)
        self.port = port
        self.host = host
        self._server = None
        self._server_thread = None
        self._setup_routes()

    def _setup_routes(self):
        # 根路径响应
        @self.app.route('/')
        def root_path():
            return Response("自动化", mimetype='text/plain')

        # HTML格式响应
        @self.app.route('/html/')
        def html_response():
            html_content = """
            <!DOCTYPE html>
            <html>
            <head><title>自动化测试</title></head>
            <body>
                <h1>自动化测试页面</h1>
                <p>当前时间戳：<span id="timestamp">{}</span></p>
            </body>
            </html>
            """.format(time.time())
            return Response(html_content, mimetype='text/html')

        # XML格式响应
        @self.app.route('/xml/')
        def xml_response():
            xml_content = """<?xml version="1.0" encoding="UTF-8"?>
        <Library xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:noNamespaceSchemaLocation="books.xsd">
          <Book id="B101">
            <Title>Database Design</Title>
            <Author>Alan Turing</Author>
            <Year>2022</Year>
            <Price>45.99</Price>
          </Book>
          <Book id="B102">
            <Title>Web Development Basics</Title>
            <Author>Grace Hopper</Author>
            <Year>2020</Year>
            <Price>32.50</Price>
          </Book>
        </Library>""".format(time.time())
            return Response(xml_content, mimetype='application/xml')

        # JSON格式响应
        @self.app.route('/json/')
        def json_response():
            # 解析敏感词参数
            json = request.args.get('json', type=str)
            if not json:
                return jsonify({
              "action": "create",
              "userId": "1234",
              "username": "user_123"
            }
                )
            else:
                return Response(
                    "内容非json",
                    status=200,
                    mimetype='application/json'
                )


        # 纯文本响应
        @self.app.route('/text/')
        def text_response():
            return Response("这是纯文本内容", mimetype='text/plain')

        # 敏感信息响应（带自定义响应头）
        @self.app.route('/sensitive_word/')
        def sensitive_response():
            # 解析敏感词参数
            sensitive_word = request.args.get('sensitive_word', type=str)

            # 如果没有传参则返回错误
            if not sensitive_word:
                return Response(
                    "Missing sensitive_word parameter",
                    status=200,
                    mimetype='text/plain'
                )

            # 解析自定义响应头参数
            custom_headers = {}
            headers_param = request.args.get('headers')

            if headers_param:
                try:
                    decoded_param = unquote(headers_param)
                    header_pairs = decoded_param.split(';')
                    for pair in header_pairs:
                        if '=' in pair:
                            key, value = pair.split('=', 1)
                            custom_headers[key.strip()] = value.strip()
                except Exception as e:
                    print(f"Header parse error: {str(e)}")

            # 构建响应对象
            response = Response(sensitive_word, mimetype='text/plain')

            # 添加自定义头
            for key, value in custom_headers.items():
                response.headers[key] = value

            return response

    def start(self):
        """启动生产级服务器"""
        self._server = make_server(
            host=self.host,
            port=self.port,
            app=self.app,
            threaded=True
        )
        self._server_thread = threading.Thread(target=self._server.serve_forever)
        self._server_thread.daemon = True
        self._server_thread.start()
        # print(f"高级模拟服务器运行在 http://{self.host}:{self.port}")

    def stop(self):
        """安全关闭服务器"""
        if self._server:
            self._server.shutdown()
            self._server_thread.join(timeout=5)
            # print("服务器已优雅停止")


# 使用示例
if __name__ == '__main__':
    server = AdvancedMockServer(port=5000)
    try:
        server.start()
        # 保持主线程运行
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        server.stop()